package luaweb

import (
	"bytes"
	"fmt"
	"log"
	"net/http"
	"os"
	"time"

	"gitee.com/haodreams/golib/autoroute/controller"
	"gitee.com/haodreams/golib/logs"
	lua "github.com/yuin/gopher-lua"
)

var initLua func(l *lua.LState)

func SetInitLua(f func(l *lua.LState)) {
	initLua = f
}

// LuaController 授权相关的操作
type LuaController struct {
	controller.Controller
}

func (m *LuaController) check(script string) (err error) {
	l := lua.NewState()
	err = l.DoString(script)
	if err != nil {
		return
	}
	return err
}

// Check 检查代码
func (m *LuaController) Check() {
	param := m.GetParam()
	script := param.GetTrimString("lua")
	err := m.check(script)
	if err != nil {
		m.Error(err.Error())
		return
	}
	m.Msg("OK")
}

// Test 测试代码
func (m *LuaController) Test() {
	f := m.GetParam().GetTrimString("func")
	//f = strings.ReplaceAll(f, "run", "calc")
	f = "\nfunction MyWarpFunction() \n  return " + f + "\nend"
	script := m.GetParam().GetTrimString("lua")
	script += "\n" + f
	//log.Println(script)
	l := lua.NewState()
	if initLua != nil {
		initLua(l)
	}
	err := l.DoString(script)
	if err != nil {
		m.Error(err.Error())
		return
	}
	//验证函数是否正确
	runTime := time.Now()
	err = l.CallByParam(
		lua.P{
			Fn:      l.GetGlobal("MyWarpFunction"),
			NRet:    4,
			Protect: true,
		})
	if err != nil {
		m.Error(err.Error())
		return
	}

	s := bytes.NewBuffer(nil)

	for i := 0; i < l.GetTop(); i++ {
		value := l.Get(i + 1)
		if value.Type().String() == "nil" {
			continue
		}
		log.Println(value.Type().String())
		if value == nil {
			continue
		}
		s.WriteString(fmt.Sprintln(value))
	}

	logs.Info("运行耗时:", time.Since(runTime))
	m.Msg(s.String())
}

// Save 保存代码
func (m *LuaController) Save() {
	fileName := m.GetParam().GetTrimString("name")
	if fileName == "" {
		m.Error("无效的文件名")
		return
	}
	script := m.GetParam().GetTrimString("lua")
	err := m.check(script)
	if err != nil {
		m.Error(err.Error())
		return
	}
	err = os.WriteFile("lua/"+fileName, []byte(script), 0644)
	if err != nil {
		m.Error(err.Error())
		return
	}
	m.Msg("OK")
}

// File .
func (m *LuaController) File() {
	path := "lua/" + m.GetParam().GetString("path")
	data, err := os.ReadFile(path)
	if err != nil {
		m.Error(err.Error())
	} else {
		m.Msg(string(data))
	}
}

// Tree 标签
type Tree struct {
	ID       string  `json:"id"`
	Label    string  `json:"label"`
	Icon     string  `json:"icon"`
	Children []*Tree `json:"children"`
}

// List 列出所有文件
func (m *LuaController) List() {
	path := "lua/" + m.GetParam().GetString("path")
	fi, err := os.ReadDir(path)
	if err != nil {
		m.Error(err.Error())
		return
	}
	ifs := make([]*Tree, 0, len(fi))
	for _, f := range fi {
		if f.IsDir() {
			continue
		}
		inf := new(Tree)
		inf.Label = f.Name()
		inf.ID = f.Name()
		ifs = append(ifs, inf)
	}
	m.JSON(http.StatusOK, ifs)
}
